package artid.com.arttogoa.parser;


import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;


public class BasicParser {
	public final static int Empty = -3;
	public final static int Error = -2;
	public final static int TimeOut = 0;
	public final static int Failed = -1;
	public final static int Success = 1;

	private int code = Error;
	private String fileName;
	private String msg;
	private JSONObject obj;
	protected HttpUriRequest httpUriRequest;

	public BasicParser() {

	}

	public void parse(String json) {
		tryParse(json);
		if (!isSave()) {
			return;
		}
//		if (Success == getCode()) {
//			FileUtil.saveFile(ArtWorkApp.getContext(), getFileName(),
//					json.getBytes());
//		} else {
//			 byte[] buffer = FileUtil.readFile(ArtWorkApp.getContext(),
//			 getFileName());
//			if (null != buffer) {
//				json = new String(buffer);
//				tryParse(json);
//			}
//		}
	}

	private void tryParse(String json) {
//		System.out.println("HTML:"+json);
		if (TextUtils.isEmpty(json)) {
			setCode(Error);
			setMsg("联网失败，请检查网络连接");
			return;
		}
		try {
			obj = new JSONObject(json);
			parseStatus(obj);
		} catch (JSONException e) {
			setCode(Failed);
			setMsg("请检查网络连接");
			e.printStackTrace();
		}
	}

	private void parseStatus(JSONObject obj) {
		if (obj == null) {
			return;
		}
		msg = obj.optString("msg");
		code = obj.optInt("ret");
	}

	public boolean isSave() {
		return !TextUtils.isEmpty(fileName);
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public JSONObject getObj() {
		return obj;
	}

	public HttpUriRequest getHttpUriRequest() {
		return httpUriRequest;
	}

	public void setHttpUriRequest(HttpUriRequest httpUriRequest) {
		this.httpUriRequest = httpUriRequest;
	}

}
